/** 
 * 文件名：FrameworkInterceptor.java 
 * 版本信息：1.0
 * 日期：2015年10月9日-下午5:44:07   
 */
package meterMonitor.framework.interceptors;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import meterMonitor.consts.DefinesConst;
import meterMonitor.framework.context.CurrentUser;
import meterMonitor.framework.context.SessionContext;
import meterMonitor.util.DateUtils;
import meterMonitor.util.ResourceConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;


public class FrameworkInterceptor implements HandlerInterceptor{
    
     Logger logger=LoggerFactory.getLogger(FrameworkInterceptor.class);

 	@Autowired
 	protected ResourceConfig resourceConfig;

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // TODO Auto-generated method stub
       // logger.info("进入FrameworkInterceptor拦截器preHandle方法,当前线程："+Thread.currentThread()+",时间："+System.currentTimeMillis());
        logger.info("请求url路径为："+request.getRequestURL()); 
        request.setAttribute("ctx", request.getContextPath());

        String requestUrl = request.getRequestURL().toString();

        /** 会话保留到SessionContext，以便各层使用 **/
        HttpSession session = request.getSession(true);
        logger.info("session对象:" + session);
        SessionContext.setSession(session);
        CurrentUser user = SessionContext.getCurrentUser(); //原始登录信息 无效
        boolean isLogin;
        if (user == null) {
            isLogin=false;
            SessionContext.setCurrentUser(null);
        }else {
            isLogin=true;
            session.setAttribute(DefinesConst.KEY_USER_ID, SessionContext.getCurrentUser());
            request.getSession().setAttribute("username", user.getRealName());
        }

        if (requestUrl.endsWith("/logout.do")
                //||requestUrl.endsWith("/autherror")
                || requestUrl.endsWith("/check.txt")
                ||requestUrl.endsWith("/doLogin.do")
                ||requestUrl.endsWith("/authFail.do")
                ) {
            return true;
        }

        if(isLogin){
            if (requestUrl.endsWith("/login.do")){
                response.sendRedirect("/");
            }
            return true;
        }else{
            if(request.getHeader("x-requested-with") != null &&
                    "XMLHttpRequest".equals(request.getHeader("x-requested-with"))){//ajax请求
                response.setHeader("sessionstatus", "timeout");
            }else{
                if (!requestUrl.endsWith("/login.do")){
                    response.sendRedirect("/login.do");
                }
            }
            return true;
        }

	 /*
		if (user == null) {
			if(request.getHeader("x-requested-with") != null &&
					"XMLHttpRequest".equals(request.getHeader("x-requested-with"))){//ajax请求
				response.setHeader("sessionstatus", "timeout");
			}else{
				//response.sendRedirect(request.getContextPath() + "/login");
			}
			return false;
		}else{
			//user.setIpAddress(IPUtil.getIpAddr(request));
			return true;
		}
		*/


//        Cookie memberIdCookie=CookieUtil.getCookieByName(request, "MEMBERID");
//    	String memberId=null;
//    	if(memberIdCookie!=null)
//    	{
//    		memberId=java.net.URLDecoder.decode(memberIdCookie.getValue(), "utf-8");
//    	} 
//    	boolean isLogin=true;
//    	//未登录
//		if(memberId==null||memberId.equals("")){
//			isLogin=false;
//		}  
//		else
//		{
//			try{
//				//String decMemberId =
//						DesUtil.decrypt(memberId); 
//			}
//			catch(Exception ex)
//			{
//				logger.error("非法登陆cookie:MEMBERID:"+memberId+";"+ex.getMessage(),ex);
//				isLogin=false;
//			}
//		}
//		//未登录则跳转商城登陆页面
//		if(!isLogin)
//		{
//			String loginUrl=resourceConfig.getValueByKey("member.domain");
//			response.sendRedirect(loginUrl+"Member/Login");
//			return false;
//		}
    }

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
    }

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
       // logger.info("进入FrameworkInterceptor拦截器afterCompletion方法,当前线程："+Thread.currentThread()+",时间："+System.currentTimeMillis());
        // 清除ThreadLocal中持有的信息
        SessionContext.remove();
    }

}
